﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace RRKAutohaus.Core.Repositories
{
    public class Repository<T>: IRepository<T> where T:class
    {
        protected DbContext dbContext { get; set; }
        protected DbSet<T> dbSet { get; set; }

        public Repository(DbContext dbContext)
        {
            this.dbContext = dbContext;
            this.dbSet = dbContext.Set<T>();
        }

        public void AddEntity(T entity)
        {
            DbEntityEntry dbEntityEntry = dbContext.Entry(entity);
            if (dbEntityEntry.State != EntityState.Detached)
            {
                dbEntityEntry.State = EntityState.Added;
            }
            else {
                dbSet.Add(entity);
            }

        }

        public IQueryable<T> GetAll()
        {
            return dbSet;
        }

        public T FindEntity(int id)
        {
            return dbSet.Find(id);
        }

        public IQueryable<T> FindEntity(Expression<Func<T, bool>> predicate)
        {
            return dbSet.Where(predicate);
        }

        public void UpdateEntity(T entity)
        {
            DbEntityEntry dbEntityEntry = dbContext.Entry(entity);
            if (dbEntityEntry.State == EntityState.Detached) {
                dbSet.Attach(entity);
                dbEntityEntry.State = EntityState.Modified;
            }
        }

        public void DeleteEntity(int id)
        {
            //T entity = FindEntity(id);

        }

        public int GetCount(Expression<Func<T,bool>> predicate)
        {
            return dbSet.Where(predicate).Count();
        }


    }
}
